import os
from prompt.user_profile import USER_PROFILE_PROMPT, NO_SUMMARY_FLAG
from langchain_openai import ChatOpenAI
from langchain_classic.memory import ConversationSummaryMemory, ConversationBufferWindowMemory

class UserProfile():
    """
    用于在对话过程中，从对话中进行用户期待对象的总结，使角色越来越贴近用户的期待，和用户有共同爱好。
    """
    SAVE_PATH = "./user_exp_role.txt"
    def __init__(self, chat_model : ChatOpenAI):
        self.chat_model = chat_model
        self.summarizes = ""

        if os.path.exists(self.SAVE_PATH):
            with open(self.SAVE_PATH, mode="r", encoding="utf-8") as file:
                self.summarizes = file.read()

    def save_state(self):
        print(self.summarizes)
        if self.summarizes:
            with open(self.SAVE_PATH, mode="w", encoding="utf-8") as f:
                f.write(f"{self.summarizes}")

    def summary(self, memory: ConversationBufferWindowMemory, user_input: str):
        """
        对输入的话进行总结，总结用户的理想伴侣是什么样的，形成摘要。
        """
        messages = memory.load_memory_variables({})["history"]  # 列表类型
        
        history_str = ""
        for msg in messages:
            # 根据消息类型拼接（Human/AI 对应不同前缀，可自定义）
            if msg.type == "human":
                history_str += f"用户：{msg.content}\n"
            elif msg.type == "ai":
                history_str += f"AI: {msg.content}\n"

        # 步骤2：拼接用户新输入（字符串+字符串）
        full_context = history_str + f"用户：{user_input}"

        prompt = USER_PROFILE_PROMPT.format(user_input=full_context, history=self.summarizes)
        result = self.chat_model.invoke(prompt).content.strip()
        self.summarizes = result

        # print(f"摘要：{self.summarizes}")

    



    